package com.shi.data_structure.array;

import java.beans.Customizer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

/**
 * 动态数组
 */
public class DynamicArray implements Iterable<Integer>{
    private int size = 0;//逻辑大小
    private int capacity = 8;//真实容量
    private int[] array = {};

    public void addLast(int element){
//        array[size] = element;
//        size++;

        add(size, element);
    }

    public void add(int index, int element){
        //检查容量,容量不过扩容
        CheckAndGrow();

        //index后的元素后移1位
        if(index >= 0 && index < size) {
            System.arraycopy(array, index, array, index + 1, size - index);
        }
        //插入
        array[index] = element;
        size++;
    }

    private void CheckAndGrow() {
        if(size == 0){
            array = new int[capacity];
        } else if (capacity == size){
            //扩容 java中实现：黄金比例1.68 -> 1.5倍扩容
            //capacity = capacity + (capacity >> 1);
            capacity += capacity >> 1;

            int[] newArray = new int[capacity];
            System.arraycopy(array, 0, newArray, 0, size);

            array = newArray;
        }
    }

    public int get(int index){
        return array[index];
    }

    @Override
    public String toString() {
        return "DynamicArray{" +
                "size=" + size +
                ", capacity=" + capacity +
                ", array=" + Arrays.toString(array) +
                '}';
    }

    /**
     * 遍历
     */

    /**
     * 遍历方法1 foreach遍历
     *
     * @param consumer 遍历要执行的操作, 入参: 每个元素
     */
    public void foreach(Consumer<Integer> consumer){
        for (int i = 0; i < size; i++) {
            //提供 array[i]
            //返回 void
            consumer.accept(array[i]);
        }
    }

    /**
     * 遍历方法2 迭代器遍历
     * @return
     */
    @Override
    public Iterator<Integer> iterator(){
        return new Iterator<Integer>(){
            int i = 0;

            @Override
            public boolean hasNext(){
                return i < size;
            }

            @Override
            public Integer next(){
                return array[i++];
            }
        };
    }

    /**、
     * 遍历方法3 Stream流遍历
     * @return
     */
    public IntStream stream(){
        return  IntStream.of(Arrays.copyOfRange(array, 0, size));
    }

    /**
     * 从 [0 .. size) 范围删除元素
     *
     * @param index 索引位置
     * @return 被删除元素
     */
    public int remove(int index) { // [0..size)
        int removed = array[index];
        if (index < size - 1) {
            // 向前挪动
            System.arraycopy(array, index + 1,
                    array, index, size - index - 1);
        }
        size--;
        return removed;
    }
}
